var fs = require('fs');
var path = require('path');
var read = require('../read');

function test(fileOrPath, excepts) {
  if (excepts) {
    for (var i = 0; i < excepts.length; i++) {
      if (Object.prototype.toString.call(excepts[i]) == "[object RegExp]") {
        if (excepts[i].test(fileOrPath)) {
          return true;
        }
      } else if (typeof excepts[i] === 'string') {
        if (fileOrPath.indexOf(excepts[i]) !== -1) {
          return true;
        }
      }
    }
  }
  return false;
}

function _pathRead(_file, _cb, _finish, excepts) {
  /**
   * 文件夹读完回调
   * 原来写在外面是个单例，多个文件同时使用就会错误
   * 所以写到函数内部
   */
  var count = 1;

  var pathRead = function(file, cb, finish, excepts) {

    fs.stat(file, function(err, stat) {
      if (err || test(file, excepts)) {
        count--;
        cb(err || 'excepted');
        return;
      }
      
      if (stat.isDirectory()) {
        var basePath = file;
        fs.readdir(basePath, function(err, files) {
          count--;
          count += files.length;

          for (var i = 0; i < files.length; i++) {
            var file = files[i];
            pathRead(path.resolve(basePath, file), cb, finish, excepts);
          }
        });
      } else if (stat.isFile()) {
        read.readFile(file, function(err, str) {
          count--;
          cb(err, str, file);

          if (count === 0) {
            finish && finish();
          }
        });
      }
    })
  }

  pathRead(_file, _cb, _finish, excepts);
  
}

module.exports = _pathRead;